package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.service.MenuService;
import com.itheima.mapper.MenuMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Menu;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    UserMapper userMapper;

    //查询该用户可见菜单
    @Override
    public List<Map> findMenuByUsername(String username) {
        try {

            List<Map> menu = new ArrayList();
            //查询用户对应的角色id
            Integer[] roleIds = userMapper.findRolesByUsername(username);
            if (roleIds != null && roleIds.length > 0) {
                for (int i = 0; i < roleIds.length; i++) {
                    //查询角色对应的主菜单
                    menu = baseMapper.findParentMenuByRoleIds(roleIds[i]);
                    for (Map map : menu) {
                        map.put("children", "");
                        Set set = map.keySet();
                        for (Object o : set) {
                            String key = (String) o;
                            if ("id".equals(key)) {
                                Object menuId = map.get(key);
                                String s = String.valueOf(menuId);
                                List<Map> sonMenu = baseMapper.findSonMenuByParentMenuId(s);
                                map.put("children", sonMenu);
                            }
                        }
                    }

                }
            }
            return menu;
        } catch (Exception e) {
            System.out.println("-------------------" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }
}
